/**
 * Notes: 跨项目事件总线服务
 * Date: 2025-05-01
 */

const EventModel = require('../config/models_config').event_model;
const AppError = require('../../../framework/core/app_error.js');

// 事件类型定义
const EVENT_TYPES = {
  // 项目状态变更
  PROJECT_STATUS_CHANGED: 'PROJECT_STATUS_CHANGED',
  // 审批状态变更
  APPROVAL_STATUS_CHANGED: 'APPROVAL_STATUS_CHANGED',
  // 用户状态变更
  USER_STATUS_CHANGED: 'USER_STATUS_CHANGED',
  // 部门调整
  DEPARTMENT_CHANGED: 'DEPARTMENT_CHANGED'
};

// 事件监听器管理
const eventListeners = {};

/**
 * 跨项目事件总线服务
 */
class EventBusService {
  constructor() {
    this.eventModel = new EventModel();
    
    // 初始化事件处理器
    this.initEventListeners();
  }

  /**
   * 初始化事件监听器
   */
  initEventListeners() {
    // 为每种事件类型创建空数组
    Object.values(EVENT_TYPES).forEach(type => {
      eventListeners[type] = [];
    });
  }

  /**
   * 注册事件监听器
   * @param {String} eventType 事件类型
   * @param {Function} callback 回调函数
   */
  on(eventType, callback) {
    if (!eventListeners[eventType]) {
      eventListeners[eventType] = [];
    }
    
    eventListeners[eventType].push(callback);
    console.log(`[EVENT_BUS] 注册事件监听器: ${eventType}, 当前监听器数量: ${eventListeners[eventType].length}`);
  }

  /**
   * 发布事件
   * @param {String} eventType 事件类型
   * @param {Object} eventData 事件数据
   * @returns {Promise<String>} 事件ID
   */
  async publish(eventType, eventData) {
    if (!EVENT_TYPES[eventType]) {
      throw new AppError(`未知的事件类型: ${eventType}`, 30001);
    }

    // 将事件保存到数据库
    const eventId = await this.eventModel.publishEvent(eventType, eventData);
    console.log(`[EVENT_BUS] 发布事件: ${eventType}, ID: ${eventId}`);

    // 触发事件处理
    this.processEvent(eventType, eventData, eventId);

    return eventId;
  }

  /**
   * 处理事件
   * @param {String} eventType 事件类型
   * @param {Object} eventData 事件数据
   * @param {String} eventId 事件ID
   */
  async processEvent(eventType, eventData, eventId) {
    const listeners = eventListeners[eventType] || [];
    
    if (listeners.length === 0) {
      console.log(`[EVENT_BUS] 事件 ${eventType} 没有监听器`);
      return;
    }

    try {
      // 调用所有监听器
      const promises = listeners.map(callback => callback(eventData));
      const results = await Promise.allSettled(promises);
      
      // 统计处理结果
      const success = results.filter(r => r.status === 'fulfilled').length;
      const failed = results.filter(r => r.status === 'rejected').length;
      
      // 更新事件处理结果
      await this.eventModel.processEvent(eventId, {
        success,
        failed,
        total: listeners.length
      });
      
      console.log(`[EVENT_BUS] 事件 ${eventType} 处理完成, 成功: ${success}, 失败: ${failed}`);
    } catch (error) {
      console.error(`[EVENT_BUS] 事件处理出错: ${error.message}`);
    }
  }

  /**
   * 处理待处理事件
   * @returns {Promise<Object>} 处理结果
   */
  async processPendingEvents() {
    const pendingEvents = await this.eventModel.getPendingEvents(null, 50);
    
    if (pendingEvents.length === 0) {
      return { success: true, processed: 0 };
    }
    
    let processed = 0;
    
    for (const event of pendingEvents) {
      try {
        await this.processEvent(event.type, event.data, event._id);
        processed++;
      } catch (error) {
        console.error(`[EVENT_BUS] 处理事件 ${event._id} 失败: ${error.message}`);
      }
    }
    
    return {
      success: true,
      processed,
      total: pendingEvents.length
    };
  }
}

module.exports = {
  EventBusService,
  EVENT_TYPES
}; 